<?php

//PLUGIN type=backend
//PLUGIN name=updater
//PLUGIN desc=Enables you update your system from a remote update server
//PLUGIN group=native


global $options,$smarty;

define('UPDATER_SITE', 'tudb.org');
define('UPDATER_PASSWORD', 'password');

define('UPDATER_URL', 'http://tudb.org/projects/wideupdate/'); // Append commands to this url

$version_file = _SETTINGSPATH_ . '/system_version.ser';
if (!file_exists($version_file))
    file_put_contents($version_file, serialize(array('version' => 0.1)));

$version = unserialize(@file_get_contents($version_file));

$smarty->assign('currentSystemVersion',  floatval($version['version']));


if (empty($version))
    exit('version error on line ' . __LINE__);

if ($options['updater'])
{
    header('Content-Type: text/plain');
    if ($response = auth(UPDATER_SITE, UPDATER_PASSWORD))
    {
        print $response;
    }
    else
    {
        print "auth error";
    }
    exit();
}

function auth($site, $password)
{
    $loginString = 'site:' . $site . ';password:' . $password . ';';
    $response = file_get_contents(UPDATER_URL . $_REQUEST['q'] . $loginString);

    $a = json_decode($response, true);
    if ($a['auth']['error'])
    {
        if ($a['auth']['error'] == 'loginneeded')
        {
            return false;
        }
        elseif ($a['auth']['error'] == 'loginfailure')
        {
            return false;
        }
    }
    else
    {
        return $response;
    }
}

?>